package com.jfinal.plugin.zbus;

import com.jfinal.kit.StrKit;
import com.jfinal.log.Logger;
import com.jfinal.plugin.zbus.proto.*;
import org.reflections.Reflections;

/**
 * Created by dairymix on 17/5/8.
 */
public class ZbusAdaptor {

    private static final Logger log = Logger.getLogger(com.jfinal.plugin.zbus.ZbusAdaptor.class);

//    public enum AdaptorType{ zbus,activemq,kafka,;}

    public static ZbusAdaptor zbus = new ZbusAdaptor();

    //adaptor.zbus.broker.me //获取broker
    //adaptor.zbus.consumer.consumer //获取consumer
    //adaptor.zbus.producer.producer //获取producer

    public ZbusBroker broker = new ZbusBroker();
    public ZbusProducer producer = new ZbusProducer();
    public ZbusConsumer consumer = new ZbusConsumer();
    public ZbusQueue queue = new ZbusQueue();
    public ZbusTopic topic = new ZbusTopic();

    private ZbusAdaptor checkClass(){
        try {
            //自动扫描相关类库检查
            Class.forName("org.reflections.Reflections");
            Class.forName("com.google.common.collect.Sets");
            Class.forName("javassist.bytecode.annotation.Annotation");
        } catch (Exception e) {
            throw new RuntimeException("mq开启自动扫描加载消息处理器需要Reflections、Guava、Javassist类库，请导入相应的jar包");
        }
        return this;
    }

    private ZbusAdaptor checkRootPackage(String scanRootPackage){
        try { //检查rootPackage的有效性
            Package.getPackage(scanRootPackage);
        } catch (Exception e) {
            throw new RuntimeException("Zbus开启自动扫描时不能填写无效的空包地址");
        }
        return this;
    }

    public ZbusAdaptor autoLoadByAnnotation(String scanRootPackage){
        checkClass();//首先检查是否具有相关的库
        if(!StrKit.isBlank(scanRootPackage)){//根据root包路径进行自动扫描
            checkRootPackage(scanRootPackage);
            Reflections reflections = new Reflections(scanRootPackage);
            zbus.queue.receiverQ.autoLoadQAnno(reflections);
            zbus.topic.receiverT.autoLoadTAnno(reflections);
        }
        return this;
    }
}
